package controller

import (
	"example.com/myproject/project/global"
	"example.com/myproject/project/models"
	"example.com/myproject/project/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

/*
添加飞机 /admin/addaircraft

	{
	    "CurrentFlightNumber": "Defult",
	    "Model": "plant101",
		"SeatCount": 100,
	}
*/
func AddAircraft(c *gin.Context) {
	plant := models.Aircraft{}
	var input struct {
		CurrentFlightNumber *int   `json:"CurrentFlightNumber"`
		Model               string `json:"Model"`
		SeatCount           int    `json:"SeatCount"`
	}

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	plant.Model = input.Model
	plant.SeatCount = input.SeatCount
	if input.CurrentFlightNumber != nil && *input.CurrentFlightNumber != 0 {
		plant.CurrentFlightNumber = input.CurrentFlightNumber // 指针解引用
	} else {
		plant.CurrentFlightNumber = nil // 若无航班号则设置为 nil
	}
	plant.ServiceStartTime = time.Now()
	//fmt.Println("Add a new plant:", plant)
	if err := models.AddAircraft(plant); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"error": 0})
}

/*
创建一个航班，并将指定飞机当前航班写入

	{
	    "AircraftID": 5,
	    "departure_city": "Guangzhou",
		"arrival_city": "Shanghai",
		"departure_time": "2024-11-25 08:52:16.635",
		"flight_duration": 120
	}
*/
func Setflight(c *gin.Context) {
	var input struct {
		AircraftID      int       `json:"AircraftID"`
		Departure_city  string    `json:"departure_city"`
		Arrival_city    string    `json:"arrival_city"`
		Departure_time  time.Time `json:"departure_time"`
		Flight_duration int       `json:"flight_duration"`
	}
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var flight models.Flight
	flight.FlightDuration = input.Flight_duration
	flight.DepartureTime = input.Departure_time
	flight.DepartureCity = input.Departure_city
	flight.ArrivalCity = input.Arrival_city
	flight.FlightNumber = utils.TimeToInt(flight.DepartureTime)
	if err := global.Db.Create(&flight).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	err := global.Db.Model(&models.Aircraft{}).Where("aircraft_id = ?", input.AircraftID).Update("CurrentFlightNumber", flight.FlightNumber).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"error": 0})
}

/*
显示所有

*/
